<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.taskName" class="filter-item" clearable style="width: 200px" placeholder="请输入任务名称" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <el-table
      ref="table"
      v-loading="crud.loading"
      style="width: 100%;"
      :data="crud.data"
      @filter-change="crud.handleFilterChange"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column v-if="columns.visible('taskName')" prop="taskName" label="任务名称" min-width="150" />
      <el-table-column v-if="columns.visible('fileType')" prop="fileType" label="文档类型" />
      <el-table-column v-if="columns.visible('sourceFileName')" prop="sourceFileName" label="源文件名称" min-width="150" />
      <el-table-column v-if="columns.visible('convertFileName')" prop="convertFileName" label="转换文件名称" min-width="150" />
      <el-table-column v-if="columns.visible('jobName')" prop="jobName" label="作业名称" min-width="150" />
      <el-table-column v-if="columns.visible('status')" prop="status" label="转换结果">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'SUCCESS'" type="success">成功</el-tag>
          <el-tag v-if="scope.row.status === 'FAIL'" type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('crtUserName')" prop="crtUserName" label="操作人" />
      <el-table-column v-if="columns.visible('crtTs')" prop="crtTs" label="操作时间" min-width="150" />
      <el-table-column label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="downloadZipTemplate( scope.row,'sourceFile')">源文件</el-button>
          <el-button type="text" size="small" @click="resultDocument(scope.row,'convertFile')">结果文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination />
    <el-dialog
      v-if="crud.status.cu > 0"
      append-to-body
      :close-on-click-modal="false"
      :modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="800px"
    >
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="文档类型" prop="fileType">
          <el-select v-model="form.fileType" disabled placeholder="请选择文档类型">
            <el-option v-for="(type) in fileTypeList" :key="type" :label="type" :value="type" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件导入" prop="sdmType">
          <el-upload
            ref="upload"
            class="upload-demo"
            action=""
            :limit="1"
            :auto-upload="false"
            :on-change="handleChange"
            :file-list="fileList"
            :show-file-list="false"
          >
            <div>
              <el-button size="small" type="primary">点击上传</el-button>
            </div>
          </el-upload>
        </el-form-item>
        <el-table
          ref="table"
          style="margin-top: 10px"
          border
          :data="showFileList"
          row-key="id"
          max-height="235"
        >
          <el-table-column prop="fileName" label="文件名称" />
          <el-table-column prop="option" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="bitchTableDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="toAdd">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import convertConfigApi from '@/api/model/modelConfig.js'
import validateTaskName from '@/utils/taskNameRepeat'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@/components/Crud/expand/model/CRUD.operation.vue'
import pagination from '@crud/Pagination'
import { downloadFile } from '@/utils/index'

const defaultCrud = CRUD({
  title: 'SDM模型转换',
  url: '/api/sdm/convert/task',
  crudMethod: { ...convertConfigApi }
})

const defaultForm = {
  pkId: '',
  taskName: '',
  fileType: 'Excel',
  sourceFileName: '',
  sourceFilePath: '',
  jobName: '',
  convertFileName: '',
  convertFilePath: '',
  status: '',
  crtUserName: '',
  crtTs: '',
  fileList: []
}
export default {
  components: { crudOperation, rrOperation, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['data_transfer_table_convert_type', 'data_transfer_table_replace_type'],
  data() {
    return {
      permission: {
        add: ['admin', 'model:add'],
        edit: ['admin', 'model:edit'],
        del: ['admin', 'model:del']
      },
      rules: {
        taskName: [
          { required: true, validator: validateTaskName.bind(this, convertConfigApi, this.form), trigger: 'blur' }
        ],
        fileType: [
          { required: true, message: '文件类型不能为空', trigger: 'change' }
        ]
      },
      sourceList: [],
      convertList: [],
      replaceList: [],
      fileList: [],
      fileTypeList: ['Excel'],
      showFileList: []
    }
  },
  created() {
    this.crud.resetQuery(false)
  },
  methods: {
    [CRUD.HOOK.beforeToEdit](crud) {
      if (crud.form.pkId !== null) {
        // 用于编辑功能时获取任务名称
        crud.form.validateName = this.form.taskName
      }
    },
    [CRUD.HOOK.afterToAdd]() {
      this.showFileList = []
    },
    handleChange(file, fileList) {
      if (this.showFileList.length >= 1) {
        this.$notify({
          title: '只能上传一个文件！',
          type: 'warning',
          duration: 2500
        })
        this.fileList = []
        return false
      }
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['xls']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$notify({
          title: '上传文件必须是excel格式',
          type: 'warning',
          duration: 2500
        })
        this.fileList = []
        return false
      }
      this.fileList = fileList
      const formData = new FormData()
      this.fileList.forEach((element, i) => {
        formData.append('fileList', element.raw)
      })
      convertConfigApi.upload(formData).then(rsp => {
        rsp.forEach(filePath => {
          let fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
          if (filePath.includes('\\')) {
            fileName = filePath.substring(filePath.lastIndexOf('\\') + 1)
          }
          const dataForm = { filePath: filePath, fileName: fileName }
          this.showFileList.push(dataForm)
        })
        this.fileList = []
        // eslint-disable-next-line handle-callback-err
      }).catch((error) => {
        this.fileList = []
      })
    },
    toAdd() {
      this.$refs['form'].validate((valid) => {
        if (valid && this.checkHasScriptList()) {
          this.form.fileList = []
          this.showFileList.forEach(file => {
            this.form.fileList.push(file.filePath)
          })
          this.crud.doAdd()
        }
      })
    },
    checkHasScriptList() {
      if (this.showFileList.length < 1) {
        this.$notify({
          title: '请选择上传的文件！',
          type: 'warning',
          duration: 2500
        })
        return false
      }
      return true
    },
    bitchTableDelete(row) {
      this.$confirm(`确认删除文件【` + row.fileName + `】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showFileList = this.showFileList.filter(item => item.filePath !== row.filePath)
      }).catch(() => {
      })
    },
    // 源文件下载
    downloadZipTemplate(row, fileType) {
      crud.downloadLoading = true
      convertConfigApi.downloadFile(fileType, row.pkId).then(result => {
        downloadFile(result, row.taskName + '-文件清单', 'zip')
        crud.downloadLoading = false
      }).catch(() => {
        crud.downloadLoading = false
      })
    },
    // 结果文件下载
    resultDocument(row, fileType) {
      crud.downloadLoading = true
      convertConfigApi.convertFile(fileType, row.pkId).then(result => {
        downloadFile(result, row.taskName + '-结果文件清单', 'zip')
        crud.downloadLoading = false
      }).catch(() => {
        crud.downloadLoading = false
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

</style>
